package com.starblink.home.ui.cells

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.RegexUtils
import com.scwang.smart.refresh.layout.SmartRefreshLayout
import com.starblink.android.basic.adapter.BaseBindingVH
import com.starblink.android.basic.aroute.CommonRoute
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.dp
import com.starblink.android.basic.ext.enableCorner
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.sensorsdata.extension.businessSuffixId
import com.starblink.android.basic.sensorsdata.extension.trackData
import com.starblink.android.basic.sensorsdata.room.entity.SkAntEntity
import com.starblink.android.basic.sensorsdata.spm.GTrackerAssistUtils
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmElementDef
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.sensorsdata.spm.event.TrackEvent
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler
import com.starblink.android.basic.sensorsdata.spm.impl.SpmTrackHandler.trackProductMap
import com.starblink.android.basic.urllink.PullUpPageUtils
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.ImageUtils
import com.starblink.basic.util.ActivityStackManage
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.discover.util.ScrollCalculatorHelper2Home
import com.starblink.home.databinding.*
import com.starblink.home.ui.adapter.FeedsBannerAdapter
import com.starblink.home.ui.bean.*
import com.starblink.library.widget.databinding.CellSimpleProductCardBinding
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.videocache.cache.PreloadManager
import com.youth.banner.indicator.RectangleIndicator
import java.net.URLEncoder


class SkeletonCell(
    binding: LayoutHomeSkeletonFeedsBinding,
) :
    BaseBindingVH<RvSkeletonEntity, LayoutHomeSkeletonFeedsBinding>(binding) {

    init {
        itemView.layoutParams = StaggeredGridLayoutManager.LayoutParams(
            StaggeredGridLayoutManager.LayoutParams.MATCH_PARENT,
            StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT
        ).apply {
            isFullSpan = true
        }
    }

    override fun onBind(model: RvSkeletonEntity, position: Int) {

//        binding.layLoadingOne.vShm1.enableCorner(4.dp2px())
//        binding.layLoadingOne.vShm2.enableCorner(4.dp2px())
//        binding.layLoadingOne.vShm3.enableCorner(4.dp2px())
//
//        binding.layLoadingTwo.vShm1.enableCorner(4.dp2px())
//        binding.layLoadingTwo.vShm2.enableCorner(4.dp2px())
//        binding.layLoadingTwo.vShm3.enableCorner(4.dp2px())
//
//        binding.layLoadingThree.vShm1.enableCorner(4.dp2px())
//        binding.layLoadingThree.vShm2.enableCorner(4.dp2px())
//        binding.layLoadingThree.vShm3.enableCorner(4.dp2px())
//
//        binding.layLoadingFour.vShm1.enableCorner(4.dp2px())
//        binding.layLoadingFour.vShm2.enableCorner(4.dp2px())
//        binding.layLoadingFour.vShm3.enableCorner(4.dp2px())

    }

}

/**
 * feeds无数据
 */
class EmptyCell(
    binding: LayoutFeedsEmptyBinding,
) :
    BaseBindingVH<RvNoDataEntity, LayoutFeedsEmptyBinding>(binding) {


    init {
        itemView.layoutParams = StaggeredGridLayoutManager.LayoutParams(
            StaggeredGridLayoutManager.LayoutParams.MATCH_PARENT,
            StaggeredGridLayoutManager.LayoutParams.WRAP_CONTENT
        ).apply {
            isFullSpan = true
        }
    }

    override fun onBind(model: RvNoDataEntity, position: Int) {
        handleEmptyAnim(itemView)
    }

    //开启空视图的帧动画
    private fun handleEmptyAnim(v: View) {

    }
}

/**
 * feeds 运营推荐banner
 */
class FeedsBannerCell(
    binding: LayoutHomeFeedsOperSelectBannerBinding,
) :
    BaseBindingVH<RvFeedsOperSelBannerBean, LayoutHomeFeedsOperSelectBannerBinding>(binding) {

    override fun onBind(model: RvFeedsOperSelBannerBean, modelPosition: Int) {
        val activity = ActivityStackManage.currentActivity()
        binding.banner//添加生命周期观察者
            .setAdapter(
                FeedsBannerAdapter(
                    modelPosition,
                    ArrayList(model.materials),
                    activity
                )
            ).indicator =
            RectangleIndicator(activity)
//
//        binding.feedsOperSelect.setOnLongClickListener {
//            false
//        }

//        var datas: MutableList<MaterialVOF.MaterialDetailList> = mutableListOf()
//        datas.add(model.materials[0]!!)
//        datas.add(model.materials[0]!!)
//        datas.add(model.materials[0]!!)
//        datas.add(model.materials[0]!!)
//        binding.banner.setPageStyle(PageStyle.MULTI_PAGE)  /*设置画廊模式*/
//            .setIndicatorGravity(IndicatorGravity.CENTER) /*指示器的位置*/
//            .setAdapter(
//                FeedsBannerNewAdapter(
//                    modelPosition,
//                    activity
//                )
//            )  //设置适配器    必须
//            .setIndicatorStyle(IndicatorStyle.CIRCLE)  /*设置指示器样式*/
//            .setIndicatorSliderGap(2.dp) /*指示器的间距*/
//            .create(datas)
    }
}

/**
 * feeds 运营推荐gif
 */
class FeedsGifCell(
    binding: LayoutHomeFeedsOperSelectGifBinding,
) :
    BaseBindingVH<RvFeedsOpeSelGifBean, LayoutHomeFeedsOperSelectGifBinding>(binding) {

    override fun onBind(model: RvFeedsOpeSelGifBean, modelPosition: Int) {
        val activity = ActivityStackManage.currentActivity()
        ImageUtils.loadGif(activity, model.material.linkUrl, binding.gif)
        binding.gif.setOnClickListener {
            YYLogUtils.e("feeds gif ---》${model.material.jumpUrl}")
            model.material.jumpUrl?.let {
                PullUpPageUtils.routePageIntercept4Url(
                    activity = activity,
                    url = it
                )
            }
        }
        binding.gif.trackData(
            page = SpmPageDef.Home080Page_10164,
            element = SpmElementDef.HomeNewOperationSelect_33012,
            params = mapOf(
                "id" to model.material.materialId.toString(),
                "index" to modelPosition.toString()
            )
        )
    }
}

/**
 * feeds 运营推荐video
 */
class FeedsVideoCell(
    var context: Activity,
    binding: LayoutHomeFeedsOperSelectVideoBinding,
) :
    BaseBindingVH<RvFeedsOpeSelVideoBean, LayoutHomeFeedsOperSelectVideoBinding>(binding) {

    override fun onBind(model: RvFeedsOpeSelVideoBean, position: Int) {
        model.material.linkUrl?.let { rawUrl ->
            binding.homePrepareView.tag = model.material
            binding.homePrepareView.setThumbImg(context, rawUrl)
            PreloadManager.getInstance(context).addPreloadTask(rawUrl, position)
        }

        binding.homeVideoPlayer.click {
            model.material.jumpUrl?.let {
                PullUpPageUtils.routePageIntercept4Url(
                    activity = context,
                    url = it
                )
            }
        }
        binding.homeVideoPlayer.trackData(
            page = SpmPageDef.Home080Page_10164,
            element = SpmElementDef.HomeNewOperationSelect_33012,
            params = mapOf(
                "id" to model.material.materialId.toString(),
                "index" to position.toString()
            )
        )

    }

}


/**
 * feeds product
 */
class ProductCell(
    val activity: Activity,
    private val refreshStateView: SmartRefreshLayout,
    private val recyclerView: RecyclerView,
    val rv: RecyclerView,
    val scrollCalculatorHelper: ScrollCalculatorHelper2Home?,
    binding: CellSimpleProductCardBinding,
    val cardClick: (md: RvFeedsProductBean, p: Int) -> Unit,
) :
    BaseBindingVH<RvFeedsProductBean, CellSimpleProductCardBinding>(binding) {
    //    private val balloonWishGuide by binding.root.balloon<WishlistGuide01BalloonFactory>()


    private companion object {
        const val TAG = "HomeFeedsCells"
    }

    override fun onBind(model: RvFeedsProductBean, position: Int) {
        binding.card.bindProduct(
            refreshLayout = refreshStateView,
            recyclerView = recyclerView,
            productWrap = model,
            spmPageValue = SpmPageDef.Home080Page_10164,
            position = position,
            guideType = TAG,
            asHomePage = true
        )
        binding.card.setOnClickListener {
            model.product.productF.id?.let {
                CommonRoute.startProductDetail(
                    it,
                    model.product.productF.standardSpuIds ?: "",
                    model.product.productF
                )
            }
            cardClick(model, position)
        }
    }


}


/**
 * feeds 风向标(商品集合)
 */
class VaneCell(
    var context: Context,
    binding: LayoutHomeFeedsVaneBinding,
) :
    BaseBindingVH<RvFeedsWeatherVaneBean, LayoutHomeFeedsVaneBinding>(binding) {


    override fun onBind(model: RvFeedsWeatherVaneBean, position: Int) {

//        binding.feedsVane.enableCorner(16.dp)

        ImageUtils.loadImage(context, model.data[0].productF.mainImg, binding.vaneItem1.vaneImg)
        binding.vaneItem1.vaneTxt.text = model.data[0].productF.title

        ImageUtils.loadImage(context, model.data[1].productF.mainImg, binding.vaneItem2.vaneImg)
        binding.vaneItem2.vaneTxt.text = model.data[1].productF.title

        ImageUtils.loadImage(context, model.data[2].productF.mainImg, binding.vaneItem3.vaneImg)
        binding.vaneItem3.vaneTxt.text = model.data[2].productF.title

        ImageUtils.loadImage(context, model.data[3].productF.mainImg, binding.vaneItem4.vaneImg)
        binding.vaneItem4.vaneTxt.text = model.data[3].productF.title

        binding.vaneItem1.vaneClick.setOnClickListener { navPage(model.data[0].productF) }
        binding.vaneItem2.vaneClick.setOnClickListener { navPage(model.data[1].productF) }
        binding.vaneItem3.vaneClick.setOnClickListener { navPage(model.data[2].productF) }
        binding.vaneItem4.vaneClick.setOnClickListener { navPage(model.data[3].productF) }

        SpmTrackHandler.addSingleTrackData(
            SkAntEntity(
                event = TrackEvent.elementExposure.value,
                spmCnt = GTrackerAssistUtils.fetchElementValue(
                    SpmPageDef.Home080Page_10164,
                    SpmElementDef.HomeNewWindVane_20027
                ),
            )
        )

        model.data[0].productF.let {
            binding.vaneItem1.vaneClick.trackData(
                page = SpmPageDef.Home080Page_10164,
                element = SpmElementDef.ForYouVaneGoodsCard_20028,
                params = trackProductMap(0, it),
                exposeTime = 0f
            )
        }

        model.data[1].productF.let {
            binding.vaneItem2.vaneClick.trackData(
                page = SpmPageDef.Home080Page_10164,
                element = SpmElementDef.ForYouVaneGoodsCard_20028,
                params = trackProductMap(1, it),
                exposeTime = 0f
            )
        }
        model.data[2].productF.let {
            binding.vaneItem3.vaneClick.trackData(
                page = SpmPageDef.Home080Page_10164,
                element = SpmElementDef.ForYouVaneGoodsCard_20028,
                params = trackProductMap(2, it),
                exposeTime = 0f
            )
        }
        model.data[3].productF.let {
            binding.vaneItem4.vaneClick.trackData(
                page = SpmPageDef.Home080Page_10164,
                element = SpmElementDef.ForYouVaneGoodsCard_20028,
                params = trackProductMap(3, it),
                exposeTime = 0f
            )
        }
    }

    private fun navPage(productF: ProductF) {
        CommonRoute.startProductDetail(
            productId = productF.productId ?: "",
            standardSpuIds = productF.standardSpuIds ?: "",
            productF
        )
    }
}


/**
 * feeds 品牌合集
 */

class BrandCollCell(
    binding: LayoutHomeFeedsBrandCollBinding,
) :
    BaseBindingVH<RvFeedsBrandCollBean, LayoutHomeFeedsBrandCollBinding>(binding) {


    @SuppressLint("SetTextI18n")
    override fun onBind(model: RvFeedsBrandCollBean, position: Int) {
        model.data.brand?.brandVOF?.name.let {
            if (it == null) {
                binding.brandTxtLay.gone()
            } else {
                binding.brandTxtLay.visible()
                binding.brandTxt.text = it
            }
        }
        model.data.brand?.brandVOF?.productNum.let {
            binding.productsTxt.text = "${it?.toString() ?: "0"} Products"
        }

        model.data.interestedNum.let {
            binding.viewedTxt.text = "${it?.toString() ?: "0"} Viewed"
        }

        ImageUtils.loadImageFilterTransSkGray100(
            model.data.productList!![0].productF.mainImg,
            binding.brandImg1,
            null
        )
        ImageUtils.loadImageFilterTransSkGray100(
            model.data.productList!![1].productF.mainImg,
            binding.brandImg2,
            null
        )
        ImageUtils.loadImageFilterTransSkGray100(
            model.data.productList!![2].productF.mainImg,
            binding.brandImg3,
            null
        )
        ImageUtils.loadImageFilterTransSkGray100(
            model.data.productList!![3].productF.mainImg,
            binding.brandImg4,
            null
        )

        model.data.productList?.let {

            if (it.size > 6) {
                ImageUtils.loadImageFilterTransSkGray100(
                    model.data.productList!![4].productF.mainImg,
                    binding.brandImg5,
                    null
                )
                ImageUtils.loadImageFilterTransSkGray100(
                    model.data.productList!![5].productF.mainImg,
                    binding.brandImg6,
                    null
                )
                ImageUtils.loadImageFilterTransSkGray100(
                    model.data.productList!![6].productF.mainImg,
                    binding.brandImg7,
                    null
                )
            } else {
//                toast("警告：实际长度需要至少返回7 当前为测试模式")
            }
        }

        binding.feedsBrandColl.setOnClickListener {
            navPage(model, 0)
        }
        binding.brandImg1.setOnClickListener {
            navPage(model, 1)
        }
        binding.brandImg2.setOnClickListener {
            navPage(model, 2)
        }
        binding.brandImg3.setOnClickListener {
            navPage(model, 3)
        }
        binding.brandImg4.setOnClickListener {
            navPage(model, 4)
        }
        binding.brandImg5.setOnClickListener {
            navPage(model, 5)
        }
        binding.brandImg6.setOnClickListener {
            navPage(model, 6)
        }
        binding.brandImg7.setOnClickListener {
            navPage(model, 7)
        }

    }

    private fun navPage(model: RvFeedsBrandCollBean, position: Int) {

        model.data.brand?.brandVOF?.name?.let { brandName ->
            navigationTo(
                url = PullUpPageUtils.h5Url(
                    "/shop-activity/brand-collection?countryCode=${UserDataCenter.getLocalCountryCode()}&brandName=${
                        URLEncoder.encode(
                            brandName,
                            "utf-8"
                        )
                    }&index=${position}"
                )
            ) {
                withString("withSpm", "1")
            }
        }


    }
}

/**
 * feeds 折扣合集-多品牌折扣合集
 */
class FeedsDiscountCollectionMultiBrandCell(
    var context: Activity,
    binding: LayoutHomeFeedsDiscountMultiBrandBinding,
) :
    BaseBindingVH<RvFeedsDisCollMultiBrandBean, LayoutHomeFeedsDiscountMultiBrandBinding>(
        binding
    ) {

    override fun onBind(model: RvFeedsDisCollMultiBrandBean, position: Int) {
        binding.vMainImg.enableCorner(12.dp, "top")
        model.discountCollectionVO.imageUrl?.let {
            ImageUtils.loadImage(context, model.discountCollectionVO.imageUrl, binding.vMainImg)
        }
        if (model.discountCollectionVO.logoUrls.isNullOrEmpty().not()) {
            var url = ""
            var acronym = ""
            if (RegexUtils.isURL(model.discountCollectionVO.logoUrls!![0])) {
                url = model.discountCollectionVO.logoUrls!![0]!!
            } else {
                acronym = model.discountCollectionVO.logoUrls!![0]!!
            }
            binding.vLogo1.load(url, acronym)
            if (model.discountCollectionVO.logoUrls!!.size > 1) {
                if (RegexUtils.isURL(model.discountCollectionVO.logoUrls!![1])) {
                    url = model.discountCollectionVO.logoUrls!![1]!!
                } else {
                    url = ""
                    acronym = model.discountCollectionVO.logoUrls!![1]!!
                }
                binding.vLogo2.load(url, acronym)
            }
            if (model.discountCollectionVO.logoUrls!!.size > 2) {
                if (RegexUtils.isURL(model.discountCollectionVO.logoUrls!![2])) {
                    url = model.discountCollectionVO.logoUrls!![2]!!
                } else {
                    url = ""
                    acronym = model.discountCollectionVO.logoUrls!![2]!!
                }
                binding.vLogo3.load(url, acronym)
            }
        }
        binding.root.trackData(
            page = SpmPageDef.Home080Page_10164,
            element = SpmElementDef.HOME_DISCOUNT_COLLECTION,
            businessSuffixID = businessSuffixId(model),
        )
        binding.root.setOnClickListener {
            navigationTo(url = model.discountCollectionVO.url)
        }
    }
}

/**
 * feeds 折扣合集-单品牌折扣合集
 */
class FeedsDiscountCollectionSingleBrandCell(
    var context: Activity,
    binding: LayoutHomeFeedsDiscountSingleBrandBinding,
) :
    BaseBindingVH<RvFeedsDisCollSingleBrandBean, LayoutHomeFeedsDiscountSingleBrandBinding>(
        binding
    ) {

    override fun onBind(model: RvFeedsDisCollSingleBrandBean, position: Int) {
        //        DiscountCollectionVOF(type=3,
        //        name=Escapism Down Vest,
        //        imageUrl=https://prod-kproject-oss.starblink.co/klarna_goods/endclothing_shoes/877eb42f9eafd863be889560b4489006.jpg,
        //        discountValue=59,
        //        url=https://pre-www.g.com/shop-activity/discount-collection-detail?type=3&extValue=155945&merchantName=Pas+Normal+Studios,
        //        extValue=155945,
        //        logoUrls=[https://prod-kproject.oss-eu-central-1.aliyuncs.com/png/074cc90d-bc1b-447c-a884-ff982f7fea15.png],
        //        merchantName=Pas Normal Studios)

        model.discountCollectionVO.imageUrl?.let {
            ImageUtils.loadImage(context, model.discountCollectionVO.imageUrl, binding.vMainImg)
        }
        if (model.discountCollectionVO.logoUrls.isNullOrEmpty().not()) {
            ImageUtils.loadImage(context, model.discountCollectionVO.logoUrls!![0], binding.vLogo)
        }
        binding.vDiscount.text = "${model.discountCollectionVO.discountValue ?: 0}% OFF"
        binding.root.trackData(
            page = SpmPageDef.Home080Page_10164,
            element = SpmElementDef.HOME_DISCOUNT_COLLECTION,
            businessSuffixID = businessSuffixId(model),
        )
        binding.root.setOnClickListener {
            navigationTo(url = model.discountCollectionVO.url)
        }
    }
}

/**
 * feeds 折扣合集-订阅店铺折扣合集
 */
class FeedsDiscountCollectionSubscribeMerchantCell(
    var context: Activity,
    binding: LayoutHomeFeedsDiscountSubscribeMerchantBinding,
) :
    BaseBindingVH<RvFeedsDisCollSubscribeMerchantBean, LayoutHomeFeedsDiscountSubscribeMerchantBinding>(
        binding
    ) {

    override fun onBind(model: RvFeedsDisCollSubscribeMerchantBean, position: Int) {
        if (model.discountCollectionVO.logoUrls.isNullOrEmpty().not()) {
            ImageUtils.loadImage(context, model.discountCollectionVO.logoUrls!![0], binding.vLogo)
        }
        binding.vMerchantName.text = model.discountCollectionVO.merchantName ?: ""
        binding.vMainImg.enableCorner(10.dp)
        model.discountCollectionVO.imageUrl?.let {
            ImageUtils.loadImageFilterTransSkGray100(
                model.discountCollectionVO.imageUrl,
                binding.vMainImg,
                null
            )
        }
        binding.vDiscount.text = "${model.discountCollectionVO.discountValue ?: 0}"
        binding.root.trackData(
            page = SpmPageDef.Home080Page_10164,
            element = SpmElementDef.HOME_DISCOUNT_COLLECTION,
            businessSuffixID = businessSuffixId(model),
        )
        binding.root.setOnClickListener {
            navigationTo(url = model.discountCollectionVO.url)
        }
    }
}

/**
 * feeds 折扣合集-单类目折扣合集
 */
class FeedsDiscountCollectionSingleCategoryCell(
    var context: Activity,
    binding: LayoutHomeFeedsDiscountSingleCategoryBinding,
) :
    BaseBindingVH<RvFeedsDisCollSingleCategoryBean, LayoutHomeFeedsDiscountSingleCategoryBinding>(
        binding
    ) {

    override fun onBind(model: RvFeedsDisCollSingleCategoryBean, position: Int) {
        binding.vMainImg.enableCorner(12.dp, "top")
        model.discountCollectionVO.imageUrl?.let {
            ImageUtils.loadImage(context, model.discountCollectionVO.imageUrl, binding.vMainImg)
        }
        binding.vDiscount.text = "${model.discountCollectionVO.discountValue ?: 0}"
        binding.root.trackData(
            page = SpmPageDef.Home080Page_10164,
            element = SpmElementDef.HOME_DISCOUNT_COLLECTION,
            businessSuffixID = businessSuffixId(model),
        )
        binding.root.setOnClickListener {
            navigationTo(url = model.discountCollectionVO.url)
        }
    }
}











